var _GET = new Array();
var _globals = new Array();
_globals["user"] = new Array();
_globals["defines"] = new Array();
_globals["timers"] = new Array();
function _new(tagName){
    return document.createElement(tagName);
}
function _getE(elementId){
    return document.getElementById(elementId)
}
function exec(data,callback)
{
    data.user_id = _globals["user"]["uid"];
    data.auth_key = _GET["auth_key"];
    $.ajax({
        type: 'POST',
        url: _globals["defines"]["SERVER_URL"],
        data:data,
        dataType:'json',
        success: callback
    });
}
function start()
{
    _globals["defines"]["SERVER_URL"] = 'http://world.ljrate.ru/server/index.php';
    _globals["obj"] = new Array();
    _globals["obj"]["interface"]= new Array();
    
    _GET = allRequestParameters();
    VK.init(function() {
        getUserInfo();
    });
}

function getRequestParameter(name,source_)
{
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
    if(!source_)source_=window.location.href;
    var results = regex.exec(window.location.href);
    return results == null ? "" : results[1];
}


function allRequestParameters(source_)
{
    var data = {};
    var strHref = window.location.href;
    if(!source_) strHref = window.location.href; else strHref = source_;

    if ( strHref.indexOf("?") > -1 ) {

        var strQueryString = strHref.substr(strHref.indexOf("?")+1);
        var aQueryString = strQueryString.split("&");
        for ( var iParam = 0; iParam < aQueryString.length; iParam++ ) {
            var aParam = aQueryString[iParam].split("=");
            data[aParam[0]] = aParam[1];
        }
    }
    return data;
}



function getUserInfo(viewer_id)
{
    VK.api('getProfiles',{
        uids:_GET['viewer_id'],
        fields:'uid,first_name,last_name,sex,bdate,photo,photo_medium,rate'
    },onGetUserInfo);
}

function onGetUserInfo(data)
{

    if(data && data.response && data.response[0])
    {
        for(var i in data.response[0])
            _globals["user"][i] = data.response[0][i];
    }
    getFriends();
}

function getFriends()
{
    VK.api('friends.getAppUsers',{},onGetFriends);
}

function onGetFriends(data)
{
    if(data)
    {
        if(data.response)
        {
            _globals["obj"]["friends"] = new Array();
            str = data.response.toString();
            _globals["obj"]["friends_string"] = str;
            var friends_array = data.response;
            var friend_count = 0;
            for(var i in friends_array)
            {
                if(friends_array[i] && typeof(friends_array[i]) != 'object')
                {
                    friend_count++;
                }
                _globals["obj"]["friends"][friends_array[i]] = new Array();
                _globals["obj"]["friends"][friends_array[i]]["loaded"] = false;
            }
            if(friend_count)
            {
                getFriendsInfo(friends_array);
            }
            else
            {
                _globals["obj"]["friends_string"] = '';
                getFriendsInfo(false);
            }
        }
    }
}

function getFriendsInfo(uids)
{
    if(!uids) 
    {
        onGetFriendsInfo(false);
        return true;
    }
    var uids_string = '';
    for(i in uids)
    {
        uids_string += uids[i]+',';
    }

    VK.api('getProfiles',{
        uids:uids_string,
        fields:'uid,first_name,last_name,sex,bdate,photo,photo_medium,rate'
    },onGetFriendsInfo);
    return true;
}

function onGetFriendsInfo(data)
{
    if(data)
    {
        if(data.response)
        {
            var one_user = {};
            for(var i in data.response)
            {
                one_user = data.response[i];
                if(one_user && one_user["uid"] && _globals["obj"]["friends"][one_user["uid"]])
                {
                    for(var j in one_user)
                    {
                        _globals["obj"]["friends"][one_user["uid"]][j] = one_user[j];
                    }
                }
            }
        }
    }
    initServer();
}

function initServer()
{
    var data = {};
    // method
    data.method = 'init';
    // profile
    data.first_name = _globals["user"]["first_name"];
    data.last_name = _globals["user"]["last_name"];
    data.sex = _globals["user"]["sex"];
    data.age = _globals["user"]["bdate"];
    // appfriends
    data.friends = _globals["obj"]["friends_string"];
    exec(data, onInitServer)
}

function onInitServer(data)
{
    var temp = new Array();
    _globals["timers"]["main"] = setInterval(Main_timer,1000);
    if(data.response && data.response.profile)
    {
        for(var x in data.response.profile)
        {
            _globals["user"][x] = data.response.profile[x];
        }
    }
    if(data && data.response)
    {
        if(data.time) SyncServer(data.time-0);
        for (var n in data.response)
        {
            if(n != 'friends' && n!= 'profile')
            {
                _globals["obj"][n] = data.response[n];
            }
        }
        // only answer friends will left
        var temp_sorted = new Array();
        if(data.response.friends)
        {
            for(var i in _globals["obj"]["friends"])
            {
                if(data.response.friends['u'+i])
                {
                    temp['u'+i] = _globals["obj"]["friends"][i];
                    for(var j in data.response.friends['u'+i])
                    {
                        temp['u'+i][j] = data.response.friends['u'+i][j];
                    }
                }
            //else not registered on server but appfriend
            }
            var self_sorted = false;
            for (i in data.response.friends)
            {
                if(temp[i])
                {
                    if(!self_sorted && temp[i]["exp"]-0 > _globals["user"]["exp"]-0)
                    {
                        self_sorted = true;
                        temp_sorted['u'+_globals["user"]["user_id"].toString()] = _globals["user"];
                    }
                    temp_sorted[i] = temp[i];
                }
            }
            if(!self_sorted)
            {
                // значит будем последними
                _globals["user"]['visited'] = 1;
                temp_sorted['u'+_globals["user"]["user_id"].toString()] = _globals["user"];
            }
        }
        else
        {
            temp_sorted['u'+_globals["user"]["user_id"].toString()] = _globals["user"];
        }

        if(is_chrome) temp_sorted.sort(friends_chrome_sort);

        _globals["obj"]["friends"] = temp_sorted;
        call_drawMap();
    }
}

    function call_drawMap()
    {
        start_map(); 
    }